package com.jeejio.gerritmanage.controller;

import com.jeejio.gerritmanage.config.ApplicationConfiguration;
import com.jeejio.gerritmanage.config.Constant;
import com.jeejio.gerritmanage.util.InvitationUtil;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

@RequestMapping("/user")
@Controller
public class UserController {

    @ResponseBody
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public String addUser(@RequestBody String param) {
        JSONObject json = new JSONObject(param);
        JSONObject ret = new JSONObject();
        if ((!json.has("invitationCode"))
                || (!json.has("name"))
                || (!json.has("pwd"))) {
            ret.put("code", 0);
            ret.put("msg", "用户名、密码及邀请码不能为空");
            return ret.toString();
        }
        String name = json.getString("name");
        String pwd = json.getString("pwd");
        String invitationCode = json.getString("invitationCode");
        if ((null == name) || ("".equals(name.trim()))
            || (null == pwd) || ("".equals(pwd))
            || (null == invitationCode) || ("".equals(invitationCode.trim()))) {
            ret.put("code", 0);
            ret.put("msg", "用户名、密码及邀请码不能为空");
            return ret.toString();
        }

        // 去重
        List<String> list = getUserList();
        for (String user : list) {
            if (user.equalsIgnoreCase(name)) {
                ret.put("code", 0);
                ret.put("msg", "用户已存在！");
                return ret.toString();
            }
        }

        try {
            String code = InvitationUtil.getCode();
            if (!code.equals(invitationCode)) {
                ret.put("code", 0);
                ret.put("msg", "邀请码不正确");
                return ret.toString();
            }
            InvitationUtil.genericCode();
        } catch (IOException e) {
            e.printStackTrace();
            ret.put("code", 0);
            ret.put("msg", "读取邀请码发生错误");
            return ret.toString();
        }

        try {
            Runtime.getRuntime().exec("htpasswd -b " + Constant.APP_CONF.pwdFile + " " + name + " " + pwd);
        } catch (IOException e) {
            ret.put("code", 0);
            ret.put("msg", "用户创建失败：" + e.getMessage());
            return ret.toString();
        }
        ret.put("code", 1);
        ret.put("msg", "用户[" + name + "]创建成功！");
        return ret.toString();
    }

    @ResponseBody
    @RequestMapping(value = "/getAllUser")
    public String getAllUser() {
        JSONArray jArray = new JSONArray();
        List<String> list = getUserList();
        for (String name : list) {
            jArray.put(name);
        }
        return jArray.toString();
    }

    private List<String> getUserList() {
        List<String> list = new ArrayList<>();
        File file = new File(Constant.APP_CONF.pwdFile);
        if (file.exists()) {
            BufferedReader reader = null;
            try {
                reader = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
                String line = null;
                while ((line = reader.readLine()) != null) {
                    String[] part = line.split(":", 2);
                    if (part.length > 1) {
                        list.add(part[0]);
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (null != reader) {
                    try {
                        reader.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        return list;
    }
}
